# This Python file uses the following encoding: utf-8
import sys
from pathlib import Path
import logging
import os
from PySide6.QtCore import QUrl, QResource, QSettings, QStandardPaths
from PySide6.QtGui import QGuiApplication, QIcon
from PySide6.QtQml import QQmlApplicationEngine
from PySide6.QtAsyncio import QAsyncioEventLoop

from PySide6.QtQuickControls2 import QQuickStyle
import resource_rc  # 导入资源文件

from PySide6.QtQml import qmlRegisterType

from RaPair import RaPair  # import 使其自动注册为 QML 类型
from utils.SerialPortInfo import SerialPortInfo  # import 使其自动注册为 QML 类型
from FlashTool.FlashTool import FlashTool  # import 使其自动注册为 QML 类型

from MowerClient.ThreadedAdbClient import ThreadedAdbClient
from MowerClient.ThreadedSshClient import ThreadedSshClient
import time

from utils.AdbSetup import *

# 配置日志
logging.basicConfig(
    level=logging.DEBUG,
    format='%(asctime)s - %(levelname)s - %(message)s',
    handlers=[
        logging.FileHandler('app.log', encoding='utf-8'),  # 输出到文件
        logging.StreamHandler(sys.stdout)  # 输出到控制台
    ]
)


if __name__ == "__main__":
    # 在创建应用之前设置环境变量
    os.environ["QT_QUICK_CONTROLS_CONF"] = ":/qtquickcontrols2.conf"
    logging.getLogger("paramiko").setLevel(logging.WARNING)
    setup_adb()
    app = QGuiApplication(sys.argv)
    app.setWindowIcon(QIcon(":icons/app.ico"))
    app.setOrganizationName("Some Company")
    app.setOrganizationDomain("somecompany.com")
    app.setApplicationName("Amazing Application")
    # clinet = ThreadedAdbClient()
    # clinet.connect()
    # clinet.getBlePairingCode()
    # clinet.updateInstall("./ccc.tar.gz")
    # config_file_path = QStandardPaths.writableLocation(QStandardPaths.AppConfigLocation) + "/config.ini"
    # logging.info(f"Config file path: {config_file_path}")
    # app_settings = QSettings(config_file_path, QSettings.IniFormat)
    
    # QSettings.setDefaultFormat(QSettings.IniFormat)
    # QSettings.setPath(QSettings.IniFormat, QSettings.UserScope, QStandardPaths.writableLocation(QStandardPaths.AppConfigLocation))
    
    # 使用 qrc 路径格式
    engine = QQmlApplicationEngine()
    
    # engine.rootContext().setContextProperty("appSettings", app_settings)
    
    # 获取当前文件所在目录
    current_dir = Path(__file__).parent

    # 添加 QML 目录到导入路径
    qml_dir = current_dir / "qml"
    engine.addImportPath(str(qml_dir))
    
    tools_dir = qml_dir / "tools"
    engine.addImportPath(str(tools_dir))

    logging.info(f"QML engine import path: {engine.importPathList()}")
    
    qml_file = qml_dir / "main.qml"
    engine.load(qml_file)
    if not engine.rootObjects():
        sys.exit(-1)
    ret = app.exec()
    time.sleep(0.1)
    sys.exit(ret)
